package com.hdcircles.autoform.presenter;

import com.hdcircles.autoform.base.RxPresenter;
import com.hdcircles.autoform.component.RxBus;
import com.hdcircles.autoform.model.bean.NightModeEvent;
import com.hdcircles.autoform.model.bean.User;
import com.hdcircles.autoform.model.http.HttpResponse;
import com.hdcircles.autoform.model.http.RetrofitHelper;
import com.hdcircles.autoform.presenter.contract.MainContract;
import com.hdcircles.autoform.util.RxUtil;

import javax.inject.Inject;

import rx.Observer;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by hdcircles on 2016/9/23.
 */

public class MainPresenter extends RxPresenter<MainContract.View> implements MainContract.Presenter {

    private RetrofitHelper retrofitHelper;

    @Inject
    public MainPresenter(RetrofitHelper retrofitHelper){
        this.retrofitHelper=retrofitHelper;
    }

    void registerEvent(){
        Subscription rxSubscription= RxBus.getDefault().toObservable(NightModeEvent.class)
                .compose(RxUtil.<NightModeEvent>rxScheduleHelper())
                .map(new Func1<NightModeEvent, Boolean>() {
                    @Override
                    public Boolean call(NightModeEvent nightModeEvent) {
                        return nightModeEvent.isNightMode();
                    }
                })
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError("切换模式失败");
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        mView.useNightMode(aBoolean);
                    }
                });
        addSubscribe(rxSubscription);

    }


    @Override
    public void getUser(String email) {
        Subscription subscription=retrofitHelper.getUser(email)
                .compose(RxUtil.<HttpResponse<User>>rxScheduleHelper())
                .compose(RxUtil.<User>handleResult())
                .subscribe(new Action1<User>() {
                    @Override
                    public void call(User user) {
                        mView.showUser(user);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError(throwable.getMessage());
                    }
                });
        addSubscribe(subscription);
    }
}
